<template>
  <div class="consultation-records">
    <div class="page-header">
      <h2>咨询记录管理</h2>
    </div>

    <el-table
      v-loading="loading"
      :data="records"
      style="width: 100%"
    >
      <el-table-column prop="id" label="ID" width="80" />
      
      <el-table-column label="咨询者" min-width="120">
        <template #default="{ row }">
          <div class="user-info">
            <el-avatar :size="30" :src="row.userAvatar || '/default-avatar.png'" />
            <span>{{ row.username }}</span>
          </div>
        </template>
      </el-table-column>

      <!-- 只有管理员才显示咨询师列 -->
      <el-table-column v-if="!isExpert" label="咨询师" min-width="120">
        <template #default="{ row }">
          <div class="user-info">
            <el-avatar :size="30" :src="row.consultantAvatar || '/default-avatar.png'" />
            <span>{{ row.consultantName }}</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'info'">
            {{ row.status === 1 ? '进行中' : '已结束' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="createdAt" label="开始时间" width="180">
        <template #default="{ row }">
          {{ formatDateTime(row.createdAt) }}
        </template>
      </el-table-column>

      <el-table-column prop="endedAt" label="结束时间" width="180">
        <template #default="{ row }">
          {{ row.endedAt ? formatDateTime(row.endedAt) : '-' }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button 
            type="primary" 
            link
            @click="viewMessages(row)"
          >
            查看对话
          </el-button>
          <el-button 
            v-if="row.status === 1"
            type="danger" 
            link
            @click="endConsultation(row)"
          >
            结束咨询
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 对话内容弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="咨询对话记录"
      width="60%"
      :destroy-on-close="true"
      @close="handleDialogClose"
    >
      <div class="messages-container" ref="messagesContainer">
        <div 
          v-for="(message, index) in messages" 
          :key="index"
          :class="['message', message.fromUser ? 'message-right' : 'message-left']"
        >
          <el-avatar 
            :size="30" 
            :src="message.fromUser ? currentRecord?.userAvatar : currentRecord?.consultantAvatar"
          />
          <div class="message-content">
            <div class="message-text">{{ message.content }}</div>
            <div class="message-time">{{ formatDateTime(message.createdAt) }}</div>
          </div>
        </div>
      </div>
      <!-- 添加消息输入框 -->
      <div class="input-area">
        <el-input
          v-model="inputMessage"
          type="textarea"
          :rows="3"
          placeholder="请输入消息..."
          @keyup.enter.native.exact="sendMessage"
        />
        <el-button type="primary" @click="sendMessage" :loading="sending">
          发送
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import Cookies from 'js-cookie'
import WebSocketClient from '@/utils/websocket'

const loading = ref(false)
const records = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const dialogVisible = ref(false)
const messages = ref([])
const currentRecord = ref(null)
const messagesContainer = ref(null)
const inputMessage = ref('')
const sending = ref(false)

const userInfo = ref(JSON.parse(Cookies.get('userInfo') || '{}'))
const isExpert = userInfo.value.role === 'EXPERT'

// 创建WebSocket实例
const ws = new WebSocketClient()

// 获取咨询记录列表
const fetchRecords = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value
    }
    
    // 如果是专家，使用consultant接口，否则使用普通列表接口
    const url = isExpert ? '/admin/consultation/consultant' : '/admin/consultation'
    const res = await request.get(url, { params })
    
    if (res.data) {
      records.value = res.data.records
      total.value = res.data.total
    }
  } catch (error) {
    console.error('获取咨询记录失败:', error)
    ElMessage.error('获取咨询记录失败')
  } finally {
    loading.value = false
  }
}

// 查看对话记录
const viewMessages = async (row) => {
  currentRecord.value = row
  dialogVisible.value = true
  
  try {
    // 获取历史消息
    const res = await request.get(`/admin/consultation/${row.id}/messages`)
    if (res.data) {
      messages.value = res.data.records
      
      // 建立WebSocket连接
      ws.connect(`/ws/consultation/${row.id}/${userInfo.value.id}`)
      ws.addMessageHandler(handleMessage)
      
      scrollToBottom()
    }
  } catch (error) {
    console.error('获取对话记录失败:', error)
    ElMessage.error('获取对话记录失败')
  }
}

// 处理接收到的消息
const handleMessage = (message) => {
  console.log('收到WebSocket消息:', message)
  // 直接使用接收到的消息对象
  const formattedMessage = {
    content: message.content,
    fromUser: message.senderId === userInfo.value.id,
    createdAt: message.createdAt || new Date().toISOString()
  }
  console.log('格式化后的消息:', formattedMessage)
  messages.value.push(formattedMessage)
  scrollToBottom()
}

// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim()) {
    return
  }

  sending.value = true
  const messageContent = inputMessage.value.trim()
  
  try {
    // 使用HTTP请求发送消息
    const res = await request.post('/admin/consultation/message/send', {
      consultationId: currentRecord.value.id,
      content: messageContent,
      senderId: userInfo.value.id,
      receiverId: isExpert ? currentRecord.value.userId : currentRecord.value.consultantId,
      userId: userInfo.value.id
    })
    
    if (res.code === 200) {
      // 清空输入框
      inputMessage.value = ''
      
      // 立即将消息添加到本地列表，使用fromUser属性
      messages.value.push({
        content: messageContent,
        fromUser: true, // 设置为true表示是自己发送的消息
        createdAt: new Date().toISOString()
      })
      scrollToBottom()
    } else {
      ElMessage.error(res.msg || '发送消息失败')
    }
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('发送消息失败')
  } finally {
    sending.value = false
  }
}

// 关闭对话框时断开WebSocket连接
const handleDialogClose = () => {
  ws.removeMessageHandler(handleMessage)
  ws.disconnect()
}

// 结束咨询
const endConsultation = async (row) => {
  try {
    await ElMessageBox.confirm('确定要结束此次咨询吗？', '提示', {
      type: 'warning'
    })
    
    await request.post(`/admin/consultation/${row.id}/end`)
    ElMessage.success('咨询已结束')
    fetchRecords()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('结束咨询失败:', error)
      ElMessage.error('结束咨询失败')
    }
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  fetchRecords()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchRecords()
}

const formatDateTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  })
}

const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

onMounted(() => {
  fetchRecords()
})
</script>

<style scoped>
.consultation-records {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 500;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.messages-container {
  height: 500px;
  overflow-y: auto;
  padding: 20px;
  background-color: #f5f5f5;
}

.message {
  display: flex;
  align-items: flex-start;
  margin-bottom: 20px;
  gap: 10px;
}

.message-right {
  flex-direction: row-reverse;
}

.message-content {
  max-width: 70%;
}

.message-text {
  padding: 10px 15px;
  border-radius: 4px;
  background-color: #fff;
  word-break: break-all;
}

.message-right .message-text {
  background-color: #95ec69;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
  text-align: right;
}

.input-area {
  margin-top: 20px;
  display: flex;
  gap: 10px;
}

.input-area .el-textarea {
  flex: 1;
}

.input-area .el-button {
  align-self: flex-end;
}
</style>